package org.duiduo.config;

import cn.hutool.core.date.DatePattern;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import lombok.extern.slf4j.Slf4j;
import org.duiduo.util.RedisUtil;
import org.noear.solon.annotation.Bean;
import org.noear.solon.annotation.Condition;
import org.noear.solon.annotation.Configuration;
import org.noear.solon.annotation.Inject;
import org.redisson.api.RedissonClient;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.solon.RedissonClientOriginalSupplier;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * Redis配置
 *
 * @author liangze
 * @date 2025/9/29 15:04
 */
@Slf4j
@Configuration
public class RedisConfig {

    /**
     * RedissonClient
     *
     * @param supplier supplier
     * @return redisson客户端
     */
    @Bean
    public RedissonClient redissonClient(@Inject("${redis.ds1}") RedissonClientOriginalSupplier supplier) {
        log.info("Redisson加载中...");
        // 创建 RedissonClient之前设置序列化方式
        supplier.withConfig(config -> config.setCodec(new JsonJacksonCodec(newObjectMapper())));
        return supplier.get();
    }

    /**
     * Redis工具类
     *
     * @return RedisUtil
     */
    @Bean
    @Condition(onBean = RedissonClient.class)
    public RedisUtil redisService(RedissonClient redissonClient) {
        return new RedisUtil(redissonClient);
    }

    /**
     * 创建ObjectMapper
     *
     * @return ObjectMapper
     */
    private ObjectMapper newObjectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DatePattern.NORM_DATETIME_FORMATTER));
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DatePattern.NORM_DATETIME_FORMATTER));

        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DatePattern.NORM_DATE_FORMATTER));
        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DatePattern.NORM_DATE_FORMATTER));

        javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DatePattern.NORM_TIME_FORMATTER));
        javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DatePattern.NORM_TIME_FORMATTER));

        mapper.registerModule(javaTimeModule);
        return mapper;
    }

}
